from django.db import models
from django.contrib.auth import get_user_model
from imagekit.models import ImageSpecField
from imagekit.processors import ResizeToFill, ResizeToFit
from .utils import compress_image

User = get_user_model()

class SurveyRecord(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='用户')
    location_name = models.CharField(max_length=200, verbose_name='地点名称')
    address = models.TextField(verbose_name='详细地址')
    latitude = models.DecimalField(max_digits=9, decimal_places=6, null=True, blank=True, verbose_name='纬度')
    longitude = models.DecimalField(max_digits=9, decimal_places=6, null=True, blank=True, verbose_name='经度')
    orientation = models.CharField(max_length=50, blank=True, verbose_name='地理朝向')
    notes = models.TextField(blank=True, verbose_name='备注')
    survey_date = models.DateTimeField(verbose_name='勘查日期')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        verbose_name = '勘查记录'
        verbose_name_plural = '勘查记录'
        ordering = ['-survey_date']
        indexes = [
            models.Index(fields=['user', '-survey_date']),
            models.Index(fields=['user', 'location_name']),
            models.Index(fields=['user', 'survey_date']),
            models.Index(fields=['latitude', 'longitude']),
            models.Index(fields=['created_at']),
        ]

    def __str__(self):
        return f"{self.location_name} - {self.user.username}"

class SurveyImage(models.Model):
    survey_record = models.ForeignKey(SurveyRecord, on_delete=models.CASCADE, related_name='images', verbose_name='勘查记录')
    image = models.ImageField(upload_to='survey_images/', verbose_name='图片')
    orientation = models.CharField(max_length=50, blank=True, verbose_name='拍摄方向')
    uploaded_at = models.DateTimeField(auto_now_add=True, verbose_name='上传时间')
    
    # 自动生成的压缩图和缩略图
    compressed_image = ImageSpecField(
        source='image',
        processors=[ResizeToFit(1920, 1080)],
        format='JPEG',
        options={'quality': 85}
    )
    
    thumbnail = ImageSpecField(
        source='image',
        processors=[ResizeToFill(300, 300)],
        format='JPEG',
        options={'quality': 80}
    )
    
    class Meta:
        verbose_name = '勘查图片'
        verbose_name_plural = '勘查图片'
        ordering = ['-uploaded_at']
        indexes = [
            models.Index(fields=['survey_record', '-uploaded_at']),
            models.Index(fields=['uploaded_at']),
        ]
        
    def __str__(self):
        return f"{self.survey_record.location_name} - 图片"
    
    def save(self, *args, **kwargs):
        if self.image and not self.pk:
            # 压缩原图
            self.image = compress_image(self.image)
        super().save(*args, **kwargs)

class FavoriteLocation(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='用户')
    name = models.CharField(max_length=200, verbose_name='地点名称')
    address = models.TextField(verbose_name='详细地址')
    latitude = models.DecimalField(max_digits=9, decimal_places=6, null=True, blank=True, verbose_name='纬度')
    longitude = models.DecimalField(max_digits=9, decimal_places=6, null=True, blank=True, verbose_name='经度')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')

    class Meta:
        verbose_name = '常用地点'
        verbose_name_plural = '常用地点'
        unique_together = ['user', 'name']
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['user', '-created_at']),
            models.Index(fields=['user', 'name']),
            models.Index(fields=['latitude', 'longitude']),
        ]

    def __str__(self):
        return f"{self.name} - {self.user.username}"
